package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.insurance.pojo.CategoryCoefficent;
import com.itheima.sfbx.insurance.pojo.Coefficent;
import com.itheima.sfbx.insurance.mapper.CoefficentMapper;
import com.itheima.sfbx.insurance.pojo.InsuranceCoefficent;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICoefficentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.insurance.service.IInsuranceCoefficentService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.sfbx.insurance.constant.CoefficentCacheConstant;
import com.itheima.sfbx.insurance.dto.CoefficentVO;
import com.itheima.sfbx.insurance.enums.CoefficentEnum;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import lombok.extern.slf4j.Slf4j;
/**
 * @Description：系数项服务实现类
 */
@Slf4j
@Service
public class CoefficentServiceImpl extends ServiceImpl<CoefficentMapper, Coefficent> implements ICoefficentService {

    @Autowired
    private IInsuranceCoefficentService iInsuranceCoefficentService;
    @Autowired
    private ICategoryCoefficentService categoryCoefficentService;

    @Override
    public Page<CoefficentVO> findPage(CoefficentVO coefficentVO, int pageNum, int pageSize) {
        //sql：select * from coefficent where
        Page<Coefficent> page = lambdaQuery()
                .eq(StrUtil.isNotBlank(coefficentVO.getCoefficentKey()),Coefficent::getCoefficentKey,coefficentVO.getCoefficentKey())
                .like(StrUtil.isNotBlank(coefficentVO.getCoefficentKeyName()),Coefficent::getCoefficentKeyName,coefficentVO.getCoefficentKeyName())
                .eq(StrUtil.isNotBlank(coefficentVO.getDataState()),Coefficent::getDataState,coefficentVO.getDataState())
                .orderByAsc(Coefficent::getSortNo)
                .page(new Page<>(pageNum, pageSize));
        return BeanConv.toPage(page, CoefficentVO.class);
    }

    @Override
    public CoefficentVO findById(String coefficentId) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public CoefficentVO save(CoefficentVO coefficentVO) {
        Coefficent old = lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .one();
        if (old != null) {
            log.error("数据key重复");
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
        Coefficent coefficent = BeanConv.toBean(coefficentVO, Coefficent.class);
        this.save(coefficent);
        return BeanConv.toBean(coefficent, CoefficentVO.class);
    }

    @Override
    @Transactional
    public Boolean update(CoefficentVO coefficentVO) {
        //修改之前要先判断关联的冗余字段
        Coefficent old = getById(coefficentVO.getId());
        if(old==null){
            log.error("原系数项不存在");
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        if(!StrUtil.equals(coefficentVO.getCoefficentKey(),old.getCoefficentKey())){
            log.error("key不能改");
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }

        Integer count1 = iInsuranceCoefficentService.lambdaQuery()
                .eq(InsuranceCoefficent::getCoefficentKey, old.getCoefficentKey())
                .eq(InsuranceCoefficent::getDataState,"0")
                .count();
        Integer count2 = categoryCoefficentService.lambdaQuery()
                .eq(CategoryCoefficent::getCoefficentKey, old.getCoefficentKey())
                .eq(CategoryCoefficent::getDataState,"0")
                .count();
        if(count1>0||count2>0){
            log.error("已被保险或分类关联，无法修改：{}",coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        Coefficent coefficent = BeanConv.toBean(coefficentVO,Coefficent.class);
        coefficent.setUpdateBy(null);
        coefficent.setUpdateTime(null);
        return this.updateById(coefficent);
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        List<String> ids = Arrays.asList(checkedIds);
        //先把老的查出来
        List<Coefficent> olds = listByIds(ids);
        if (CollUtil.isEmpty(olds)) {
            return true;
        }
        Set<String> keySet = olds.stream().map(Coefficent::getCoefficentKey).collect(Collectors.toSet());
        Integer count1 = iInsuranceCoefficentService.lambdaQuery()
                .in(InsuranceCoefficent::getCoefficentKey, keySet)
                .eq(InsuranceCoefficent::getDataState,"0")
                .count();
        Integer count2 = categoryCoefficentService.lambdaQuery()
                .in(CategoryCoefficent::getCoefficentKey, keySet)
                .eq(CategoryCoefficent::getDataState,"0")
                .count();
        if(count1>0||count2>0){
            log.error("已被保险或分类关联，无法删除：{}",keySet);
            throw new ProjectException(CoefficentEnum.DEL_FAIL);
        }
        return removeByIds(ids);
    }

    @Override
    public List<CoefficentVO> findList(CoefficentVO coefficentVO) {
        List<Coefficent> list = lambdaQuery()
                .eq(StrUtil.isNotBlank(coefficentVO.getCoefficentKey()),Coefficent::getCoefficentKey,coefficentVO.getCoefficentKey())
                .like(StrUtil.isNotBlank(coefficentVO.getCoefficentKeyName()),Coefficent::getCoefficentKeyName,coefficentVO.getCoefficentKeyName())
                .eq(StrUtil.isNotBlank(coefficentVO.getDataState()),Coefficent::getDataState,coefficentVO.getDataState())
                .list();
        return BeanConv.toBeanList(list, CoefficentVO.class);
    }

    @Override
    public CoefficentVO findByCoefficentKey(String coefficentKey) {
        Coefficent one = lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentKey)
                .eq(Coefficent::getDataState, SuperConstant.DATA_STATE_0)
                .one();
        return BeanConv.toBean(one,CoefficentVO.class);
    }
}
